
#include <BPainter>
#include <BRender>
#include <BViewer>
#include <BPhysics>
#include <BCone>
#include <BCube>
#include <BImage>
#include <BMaterial>
#include <BReadWrite>

#include "DynamicScene.h"
#include "HingeHandler.h"

HingeHandler::HingeHandler()
{
	BImage* image = ReadFile<BImage>("data/image/whitemetal_diffuse.jpg");

	_nodeA = new BNode("nodeA");
	{
		BPhysics* physics = new BPhysics();
		physics->setMass(10.0);
		_nodeA->setPhysics(physics);

		BCube* cube = new BCube(4, 12);
		cube->setColor(100, 200, 255);
		_nodeA->addShape(cube);

	}

	_nodeB = new BNode("nodeB");
	{
		BPhysics* physics = new BPhysics();
		physics->setMass(1.0);
		_nodeB->setPhysics(physics);

		BCone* cone = new BCone(0.5, 2, 24, 10);
		cone->setTexture(image);
		cone->setColor(200, 100, 0);
		_nodeB->addShape(cone);
	}

	BVector pointA = _nodeA->space().max() + BVector(3.5, 0, 0);
	BVector axisA(1, 0, 0);
	BVector pointB(0, 0, _nodeB->space().max().z());
	BVector axisB(0, 0, 1);
	_hingeConstraint = new BHingeConstraint(_nodeA, pointA, axisA, _nodeB, pointB, axisB);
	_hingeConstraint->setName("Hinge");
}
HingeHandler::~HingeHandler()
{

}

void HingeHandler::attached(BViewer* viewer)
{
	DynamicScene* dscene = (DynamicScene*)viewer->scene();
	_nodeA->setPosition(0, 0, 5);
	_nodeB->setPosition(2, 2, 5);
	dscene->insert(_nodeA);
	dscene->insert(_nodeB);
	dscene->insert(_hingeConstraint);
	//if (btRigidBody* bodyA = _nodeA->asset())
	//{
	//	btTransform transform;
	//	transform.setOrigin(btVector3(0, 0, 3));
	//	bodyA->setWorldTransform(transform);
	//}
	//if (btRigidBody* bodyB = _nodeB->asset())
	//{
	//	btTransform transform;
	//	transform.setOrigin(btVector3(2, 2, 3));
	//	bodyB->setWorldTransform(transform);
	//}
	this->emit("edit-constraint", _hingeConstraint);
}
void HingeHandler::detached(BViewer* viewer)
{
	DynamicScene* dscene = (DynamicScene*)viewer->scene();
	dscene->remove(_nodeA);
	dscene->remove(_nodeB);
	dscene->remove(_hingeConstraint);
}

void HingeHandler::paint(BPainter& painter)
{
	BViewer* viewer = this->viewer();
	painter.setLineWidth(10);
	painter.setColor(BColor(0, 1, 0));
	painter.drawRect(10, 10, viewer->width() - 20, viewer->height() - 20);
}
void HingeHandler::render(BRender& render)
{
	render.setLighting(false);
	render.setDepthTest(false);
	render.setLineSmooth(true);
	render.setLineWidth(1);

}
